package com.livepass.android.girlspicks.activities;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.livepass.android.girlspicks.MyApplication;
import com.livepass.android.girlspicks.R;
import com.livepass.android.girlspicks.models.Article;
import com.livepass.android.girlspicks.models.Comment;
import com.livepass.android.girlspicks.utils.JSONParser;
import com.livepass.android.girlspicks.utils.Utilities;

@SuppressLint("SetJavaScriptEnabled")
public class ReadMoreActivity extends Activity {

	private WebView notice;
	private LinearLayout llLoading;
	private UiLifecycleHelper uiHelper;
	private Article article;
	
	private AsyncPostComment loaderPostComment;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_read_more);
		
		//get article
		article = (Article) getIntent().getExtras().get("article");
		
		notice = (WebView) findViewById(R.id.webview_readmore);
		llLoading = (LinearLayout) findViewById(R.id.llLoading);
		
		notice.getSettings().setJavaScriptEnabled(true);
		//Toast.makeText(getApplicationContext(), getIntent().getStringExtra("org_url").toString(), Toast.LENGTH_SHORT).show();
		notice.loadUrl(getIntent().getStringExtra("org_url").toString());
		notice.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				llLoading.setVisibility(View.VISIBLE);				
				super.onPageStarted(view, url, favicon);
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				llLoading.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
		});		
		
		// share facebook
		uiHelper = new UiLifecycleHelper(this, null);
		uiHelper.onCreate(savedInstanceState);
	}

	@Override
	protected void onPause() {
		super.onPause();
		uiHelper.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}
	
	public void doBack(View v){
		setResult(RESULT_CANCELED);
		finish();
	}
	
	public void doComment(View view) {
		Intent intent = new Intent(this, PushCommentReplyActivity.class);
		Bundle bun = new Bundle();
		bun.putSerializable("article", article);
		intent.putExtra(MyApplication.WHERE, MyApplication.COMMENT);
		intent.putExtras(bun);
		startActivityForResult(intent, MyApplication.COMMENT);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == MyApplication.COMMENT) {
			if (resultCode == RESULT_OK) {
				String commentString = data.getStringExtra("comment");
				loaderPostComment = new AsyncPostComment(
						article.getArticleId(), commentString);
				loaderPostComment.execute();
			}
		}
	}
	
	public void doShare(View view) {
		final String link = MyApplication.APP_LINK_GLOBAL+"id="+article.getArticleId()+"&cat_id="+article.getCategoryId();
		ArrayList<String> items;
		items = new ArrayList<String>();
		items.add("Facebookでシェア");
		items.add("Twitterでシェア");
		items.add("LINEでシェア");
		items.add("リンクをコピー");
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setItems(items.toArray(new CharSequence[items.size()]),
				new DialogInterface.OnClickListener() {
					@SuppressLint("NewApi")
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							// Utilities.shareFBTapped(ArticleActivity.this,
							// "http://mp3.zing.vn/bai-hat/Weekend-Has-Come-2012-DJ/IW89E70F.html");
							if (Utilities.isPackageExisted(
									getApplicationContext(),
									"com.facebook.katana")) {
								FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
										ReadMoreActivity.this).setLink(
										link)
										.setPicture(!"".equals(article.getImage())?article.getImage():"http://girlspicks.co/img/icon.png")
										.setCaption("Girls Picks")
										.setDescription(article.getOverview())
										.setName(article.getTitle())
										.build();
								uiHelper.trackPendingDialogCall(shareDialog
										.present());
							} else {
								// Uri uri =
								// Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.katana");
								Uri uri = Uri
										.parse("https://www.facebook.com/sharer/sharer.php?u="
												+ link);
								Intent intent = new Intent(Intent.ACTION_VIEW,
										uri);
								startActivity(intent);
							}
							break;
						case 1:
							Intent intentTwitter = new Intent(
									Intent.ACTION_VIEW);
							intentTwitter.setData(Uri
									.parse("http://twitter.com/share?url="
											+ article.getTitle()+ "\n" + link + "&count=horiztonal"));
							startActivity(intentTwitter);
							break;
						case 2:
							Intent intentLine;
							if (!Utilities.isPackageExisted(
									getApplicationContext(),
									"jp.naver.line.android")) {
								Uri uri = Uri
										.parse("https://play.google.com/store/apps/details?id=jp.naver.line.android");
								// Uri uri =
								// Uri.parse("https://www.facebook.com/sharer/sharer.php?u="
								// + article.getOrgUrl());
								intentLine = new Intent(Intent.ACTION_VIEW, uri);
								startActivity(intentLine);
							} else {
								intentLine = new Intent(Intent.ACTION_SEND);
								intentLine.setType("text/plain");
								intentLine.putExtra(Intent.EXTRA_TEXT, link);

								PackageManager pm = getPackageManager();
								Intent sendIntent = new Intent(
										Intent.ACTION_SEND);
								sendIntent.setType("text/plain");
								List<ResolveInfo> resInfo = pm
										.queryIntentActivities(sendIntent, 0);
								for (int i = 0; i < resInfo.size(); i++) {
									ResolveInfo ri = resInfo.get(i);
									String packageName = ri.activityInfo.packageName;
									if (packageName
											.contains("jp.naver.line.android")) {

										intentLine.setClassName(
												ri.activityInfo.packageName,
												ri.activityInfo.name);
										startActivity(intentLine);
									}
								}

							}
							break;
						case 3:
							Toast.makeText(getApplicationContext(),
									"Copied link", Toast.LENGTH_SHORT).show();
							int sdk = android.os.Build.VERSION.SDK_INT;
							if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
								android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								clipboard.setText(link);
							} else {
								android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
								android.content.ClipData clip = android.content.ClipData
										.newPlainText("Copied Text", link);
								clipboard.setPrimaryClip(clip);
							}
							break;
						default:
							break;
						}
					}
				});
		builder.create().show();
	}
	
	private class AsyncPostComment extends AsyncTask<String, Void, String> {
		String mArticleID;
		String mTextComment;

		public AsyncPostComment(String articleId, String textComment) {
			mArticleID = articleId;
			mTextComment = textComment;
		}

		@Override
		protected String doInBackground(String... params) {
			String commentId = null;
			// post comment
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", mArticleID);
			param.put("parent_id", "0");
			param.put("client_id", MyApplication.USER_ID);
			param.put("content", mTextComment);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/set_comment", param);
				JSONParser parser = new JSONParser();
				commentId = parser.parserPostComment(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return commentId;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			llLoading.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(String result) {
			if(result != null) {
				Toast.makeText(getApplicationContext(),
						"Commented on this article.",
						Toast.LENGTH_SHORT).show();
				// get current time
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss", Locale.US);
				String currentTime = format.format(System.currentTimeMillis());
				// create comment obj
				Comment comment = new Comment();
				comment.setArticleId(mArticleID);
				comment.setCommentId(result);
				comment.setClientId(MyApplication.USER_ID);
				comment.setContent(mTextComment);
				comment.setCreatedAt(currentTime);
				comment.setUpdatedAt(currentTime);
				comment.setIsDeleted("0");
				comment.setLikeCount(0);
				comment.setDislikeCount(0);
				comment.setListReply(new ArrayList<Comment>());
			} else {
				Toast.makeText(getApplicationContext(),
						"An unexpected error has occurred when comment.",
						Toast.LENGTH_SHORT).show();
			}
			llLoading.setVisibility(View.GONE);
		}
	}

}
